import React from "react";
import {Radio as AntdRadio, Select as AntdSelect, Space as AntdSpace, Spin} from 'antd';
import {VJsonComponent} from "../../factory";
import _ from 'lodash'
import {YvanEvent} from "../../types";
import {apply, YvanEventDispatch} from "../../utils/helper";
import {DataComponentProp} from "../../datasource";
import {FormItemBaseState, FormItemVJSon, VJsonFormItemBase} from "./VJsonFormItemBase";
import * as Extend from "../../extend";
import {toJS} from "mobx";

const {Option: AntdOption} = AntdSelect;

export interface RadioVJsonProp extends FormItemVJSon<Radio> {
    size?: 'large' | 'middle' | 'small'
    onChange?: YvanEvent<Radio>
    optionType?: 'default' | 'button'
    buttonStyle?: 'outline' | 'solid'
}

export interface RadioVJsonDataProp extends RadioVJsonProp, DataComponentProp<Radio> {

}

export interface SelectState extends RadioVJsonProp, FormItemBaseState<Radio> {

}

@VJsonComponent({
    view: 'radio'
})
export default class Radio extends VJsonFormItemBase<Radio, RadioVJsonDataProp, SelectState> {
    static defaultProps = {
        ...VJsonFormItemBase.defaultProps,
        idField: 'value',
        labelField: 'label',
        loading: false,
        data: [],
        rules: [],
        visible: true
    }

    constructor(props: any) {
        super(props, Radio.defaultProps);
    }

    protected onValueChange(e: any) {
        const value = e.target.value
        this.value = value
        YvanEventDispatch(this.props.vjson.onChange, this, value)
        //YvanEventDispatch(this.state.onChange, this, value)
    }

    protected renderWrapper(): JSX.Element {
        if (Extend.isDebugMode()) {
            console.log('RenderRadio', this.toString())
        }

        const options = _.map(this.data, (item) => {
            const value = _.trim(item[this.props.vjson.idField || 'value'])
            const label = _.trim(item[this.props.vjson.labelField || 'label'])
            return {
                label, value
            }
        })

        return (
            //@ts-ignore
            <AntdRadio.Group key={this.key} view_id={this.key} aria-roledescription={this.view}
                             disabled={apply(this, this.props.vjson.disabled)}
                             size={apply(this, this.props.vjson.size)}
                             onChange={this.onValueChange.bind(this)}
                             options={options}
                             defaultValue={apply(this, this.props.vjson.defaultValue)}
                             optionType="button"
                             buttonStyle='solid'
            >
                <Spin spinning={this.loading}/>
            </AntdRadio.Group>
        )
    }
}
